import json
from flask import Flask, jsonify, request, current_app
from Day09.models import db, User
from rediscluster import StrictRedisCluster
from Day09.cache_tool import UserProfileCache
from redis.sentinel import Sentinel

app = Flask(__name__)

class Config(object):
    SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1/toutiao'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = True

    # redis 集群
    REDIS_CLUSTER = [
        {'host': '127.0.0.1', 'port': '7000'},
        {'host': '127.0.0.1', 'port': '7001'},
        {'host': '127.0.0.1', 'port': '7002'},
    ]

    # redis 哨兵
    REDIS_SENTINELS = [
        ('127.0.0.1', '26380'),
        ('127.0.0.1', '26381'),
        ('127.0.0.1', '26382'),
    ]
    REDIS_SENTINEL_SERVICE_NAME = 'mymaster'

app.config.from_object(Config)
# 为了演示效果,把集群换成主从redis
_sentinel = Sentinel(app.config['REDIS_SENTINELS'])
# 为了不改变原来的代码,把redis_master 改成redis_cluster
app.redis_cluster = _sentinel.master_for(app.config['REDIS_SENTINEL_SERVICE_NAME'])

db.init_app(app)
@app.route('/set_user_cache')
def set_user_cache():
    """
    把所有用户的数据，都缓存到redis中
    :return:
    """
    users = User.query.all()
    for user in users:
        UserProfileCache(user.id).get()
    return '缓存成功'


if __name__ == '__main__':
    app.run(host='192.168.226.129', debug=True)